let colors = [];
let requestUrl = null;

function addHandler() {
	requestUrl = "/shizhuang_category/insert";

	let parentId = $("#parent_id").combobox("getValue");

	if (parentId) {
		$("#parentId").combobox("setValue", parentId);
	}

	$("#shizhuang_dialog").dialog("open");
}

function editHandler() {
	let rowData = $("#shizhuang_list").datagrid("getSelected");

	if (rowData) {
		requestUrl = "/shizhuang_category/updateById";

		$("#id").val(rowData.id);
		$("#name").textbox("setValue", rowData.name);
		$("#type").combobox("setValue", rowData.type);
		$("#gender").combobox("setValue", rowData.gender);
		$("#colorId").combobox("setValue", rowData.colorId);
		$("#parentId").combobox("setValue", rowData.parentId);
		$("#fashion").numberspinner("setValue", rowData.fashion);

		$("#shizhuang_dialog").dialog("open");
	} else {
		alertMsg("请选择要修改的记录");
	}
}

function imageHandler() {
	let rowData = $("#shizhuang_list").datagrid("getSelected");

	if (rowData) {
		$("#shizhuang_id").val(rowData.id);
		$("#img").attr("src", rowData.image);

		$("#upload_dialog").dialog("open");
	} else {
		alertMsg("请选择要修改的记录。", "warning");
	}
}

function insertHandler() {
	requestUrl = "/shizhuang_category/insertBatch";

	let rowData = $("#shizhuang_list").datagrid("getSelected");

	if (rowData && rowData.isParent) {
		// 获取缓存的colorIds
		let colorIds = localStorage.getItem("mhxysy:colorIds");

		if (colorIds) {
			// 解析JSON字符串
			let values = JSON.parse(colorIds);

			$("#colorIds").tagbox("setValues", values);
		}

		$("#insert_dialog").dialog("open");
	} else {
		alertMsg("请选择要操作的父级时装类型。", "warning");
	}
}

function deleteHandler(shizhuangId) {
	$.messager.confirm("系统提示", "是否确认删除？", function(bool) {
		if (bool) {
			ajaxPost("/shizhuang_category/deleteById", {
				id: shizhuangId
			}, function(resp) {
				showMsg(resp.message);

				$("#shizhuang_list").datagrid("reload");
			}, error);
		}
	});
}

/**
 * 角色时装添加预览
 * @param colorId 颜色ID
 */
function viewData(colorId) {
	let rowData = $("#shizhuang_list").datagrid("getSelected");

	if (rowData && rowData.isParent) {
		let tableData = [];

		if (colors.length > 0) {
			for (let i = 0; i < colors.length; i++) {
				let color = colors[i];

				let columnData = {
					name: rowData.name + "(" + color.name + ")",
					gender: rowData.gender,
					type: rowData.type
				};

				tableData.push(columnData);
			}
		}

		let data = toJsonFormat(tableData);

		$("#view_list").datagrid("loadData", data);

		// 缓存colorIds
		let colorIds = $("#colorIds").tagbox("getValues");

		if (!contains(colorIds, colorId)) {
			colorIds.push(colorId);
		}

		localStorage.setItem("mhxysy:colorIds", JSON.stringify(colorIds));
	} else {
		alertMsg("请选择要操作的父级时装类型。", "warning");
	}
}

$(document).ready(function() {

	$("#_type_").combobox({
		url: "/shizhuang_type/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		panelHeight: "auto",
		prompt: "-时装类型-"
	});

	$("#_name_").textbox({
		width: 150,
		prompt: "输入时装名称模糊查询"
	});

	$("#_gender_").combobox({
		url: "/gender/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		prompt: "-适用性别-",
		panelHeight: "auto",
		formatter: function (row) {
			return "<img height='20' src='" + row.image + "' />" + row.name;
		}
	});

	$("#parent_id").combobox({
		url: "/shizhuang_category/selectParent",
		valueField: "id",
		textField: "name",
		width: 150,
		panelHeight: "auto",
		prompt: "-父级类型-"
	});

	$("#search").linkbutton({
		iconCls: "icon-search"
	}).click(function() {
		let parentId = $("#parent_id").combobox("getValue");
		let gender = $("#_gender_").combobox("getValue");
		let type = $("#_type_").combobox("getValue");
		let name = $("#_name_").textbox("getValue");

		$("#shizhuang_list").datagrid("reload", {
			parentId: parentId,
			gender: gender,
			name: name,
			type: type
		});
	});

	$("#clear").linkbutton({
		iconCls: "icon-delete"
	}).click(function() {
		$("#search_form").form("clear");
	});

	/******************************************************************************************************/

	$("#name").textbox({
		width: 150,
		required: true
	});

	$("#type").combobox({
		url: "/shizhuang_type/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		required: true,
		panelHeight: "auto"
	});

	$("#fashion").numberspinner({
		min: 5, // 5、8、15、30
		max: 30,
		width: 150,
		required: true
	});

	$("#gender").combobox({
		url: "/gender/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		required: true,
		panelHeight: "auto",
		formatter: function (row) {
			return "<img height='20' src='" + row.image + "' />" + row.name;
		}
	});

	$("#colorId").combobox({
		url: "/color/selectAll",
		valueField: "id",
		textField: "name",
		width: 150,
		panelHeight: "auto",
		onSelect: function (record) {
			if (record) {
				let name = $("#name").textbox("getValue");

				if (name) {
					let index = name.indexOf("(");

					if (index > 0) {
						name = name.substring(0, index)
					}

					name += "(" + record.name + ")";

					$("#name").textbox("setValue", name);
				}
			}
		}
	});

	$("#parentId").combobox({
		url: "/shizhuang_category/selectParent",
		valueField: "id",
		textField: "name",
		width: 150,
		panelHeight: "auto",
		onSelect: function (record) {
			if (record) {
				let name = $("#name").textbox("getValue");

				if (name) {
					let index = name.indexOf("(");

					if (index > 0) {
						name = record.name + name.substring(index);
					} else {
						name = record.name;
					}
				} else {
					name = record.name;
				}

				$("#name").textbox("setValue", name);
				$("#gender").combobox("setValue", record.gender);
			}
		}
	});

	$("#shizhuang_dialog").dialog({
		title: "时装信息",
		width: 500,
		buttons: [{
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let selector = "#shizhuang_form";

				checkForm(selector, function () {
					let data = $(selector).serialize();

					ajaxPost(requestUrl, data, function(resp) {
						showMsg(resp.message);

						$(selector).form("clear");
						$("#shizhuang_dialog").dialog("close");
						$("#shizhuang_list").datagrid("reload");
					}, error);
				});
			}
		}, {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				$("#shizhuang_form").form("clear");
				$("#shizhuang_dialog").dialog("close");
			}
		}]
	});

	/******************************************************************************************************/

	fetchUploadFilebox("#shizhuang_list", "/shizhuang_category/upload");

	fetchUploadDialog("/shizhuang_category/updateImageById", function () {
		$("#shizhuang_list").datagrid("reload");
	});

	/******************************************************************************************************/

	$("#colorIds").tagbox({
		url: "/color/selectAll",
		valueField: "id",
		textField: "name",
		width: 500,
		panelHeight: "auto",
		onSelect: function (record) {
			console.log("触发#colorIds的select事件...");

			let not_exists = true;

			for (let i = 0; i < colors.length; i++) {
				let color = colors[i];

				if (color === record) {
					not_exists = false;
					break;
				}
			}

			if (not_exists) {
				colors.push(record);
			}

			viewData(record.id);
		},
		onUnselect: function (record) {
			console.log("触发#colorIds的unselect事件...");

			colors = colors.filter(function (item) {
				return item.id !== record.id;
			});

			viewData(record.id);
		},
		// onRemoveTag: function (value) {
		// 	colors = colors.filter(function (item) {
		// 		return item.id !== value;
		// 	});
		//
		// 	viewData();
		// }
	});

	$("#enter").linkbutton({
		iconCls: "icon-ok",
		text: "录入"
	}).on("click", function () {
		$.messager.prompt("录入颜色", "请输入颜色名称", function(name) {
			if (name) {
				ajaxPost("/color/insert", {
					name: name
				}, function (resp) {
					showMsg(resp.message);

					colors = [];

					$("#colorIds").tagbox("reload");
				}, error);
			}
		});
	});

	$("#view_list").datagrid({
		width: 640,
		height: 300,
		fitColumns: true,
		rownumbers: true,
		columns: [[
			{field: "name", title: "时装名称", align: "center", width: 100},
			{field: "gender", title: "适用性别", align: "center", width: 100
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/gender/selectById", {
						id: value
					}, function (resp) {
						let data = resp.data;

						$("#shizhuang_gender_" + rowIndex).attr({
							"alt": data.name,
							"src": data.image,
							"title": data.name
						});
					}, error);

					return "<img id='shizhuang_gender_" + rowIndex + "' height='20' />";
				}
			},
			{field: "type", title: "时装类型", align: "center", width: 100
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/shizhuang_type/selectById", {
						id: value
					}, function (resp) {
						let data = resp.data;

						$("#shizhuang_type_" + rowIndex).html(data.name);
					}, error);

					return "<div id='shizhuang_type_" + rowIndex + "'></div>";
				}
			},
		]]
	});

	$("#insert_dialog").dialog({
		title: "批量添加",
		buttons: [{
			iconCls: "icon-save",
			text: "保存",
			handler: function() {
				let rowData = $("#shizhuang_list").datagrid("getSelected");

				if (rowData && rowData.isParent) {
					if (colors.length > 0) {
						let colorIds = $("#colorIds").tagbox("getValues");

						if (colorIds.length > 0) {
							ajaxPost(requestUrl, {
								parentId: rowData.id,
								colorIds: JSON.stringify(colorIds)
							}, function (resp) {
								showMsg(resp.message);

								$("#colorIds").tagbox("clear");
								$("#insert_dialog").dialog("close");
								$("#shizhuang_list").datagrid("reload");

								localStorage.removeItem("mhxysy:colorIds");
							}, error);
						}
					}
				} else {
					alertMsg("请选择要操作的父级时装类型。", "warning");
				}
			}
		}, {
			iconCls: "icon-cancel",
			text: "取消",
			handler: function() {
				$("#colorIds").tagbox("clear");
				$("#insert_dialog").dialog("close");

				localStorage.removeItem("mhxysy:colorIds");
			}
		}]
	});

	/******************************************************************************************************/

	/**
	 * 表格体的高度
	 * @type {number}
	 */
	let heigt_body = heigt_tr_with_image * 10;
	/**
	 * 表格高度
	 * @type {number}
	 */
	let height_table = heigt_tool + heigt_header + heigt_body + heigt_footer + heigt_scoll_bar + 2;

	$("#shizhuang_list").datagrid({
		url: "/shizhuang_category/selectByPage",
		height: height_table,
		fitColumns: true,
		pagination: true,
		toolbar: [{
			iconCls: "icon-add",
			text: "添加",
			handler: function() {
				addHandler();
			}
		}, "-", {
			iconCls: "icon-edit",
			text: "修改",
			handler: function() {
				editHandler();
			}
		}, "-", {
			iconCls: "icon-ok",
			text: "快捷添加",
			handler: function() {
				insertHandler();
			}
		}, "-", imageUpdateButton],
		columns: [[
			{field: "id", title: "编号", align: "center"},
			{field: "name", title: "时装名称", align: "center", width: 100},
			{field: "type", title: "时装类型", align: "center", width: 100
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/shizhuang_type/selectById", {
						id: value
					}, function (resp) {
						let data = resp.data;

						$("#type_" + rowIndex).html(data.name);
					}, error);

					return "<div id='type_" + rowIndex + "'></div>";
				}
			},
			{field: "colorId", title: "时装颜色", align: "center", width: 100
				, formatter: function(value, rowData, rowIndex) {
					if (value) {
						ajaxGet("/color/selectById", {
							id: value
						}, function (resp) {
							let data = resp.data;

							$("#color_" + rowIndex).html(data.name);
						}, error);

						return "<div id='color_" + rowIndex + "'></div>";
					} else {
						return "<div>/</div>";
					}
				}
			},
			{field: "image", title: "时装图片", align: "center", width: 50
				, formatter: function(value) {
					return "<img alt='暂无图片' height='" + size + "' src='" + value + "' />";
				}
			},
			{field: "fashion", title: "风尚", align: "center", width: 100},
			{field: "gender", title: "适用性别", align: "center", width: 50
				, formatter: function(value, rowData, rowIndex) {
					ajaxGet("/gender/selectById", {
						id: value
					}, function (resp) {
						let data = resp.data;

						$("#gender_" + rowIndex).attr({
							"alt": data.name,
							"src": data.image,
							"title": data.name
						});
					}, error);

					return "<img id='gender_" + rowIndex + "' height='20' />";
				}
			},
			{field: "parentId", title: "父级类型", align: "center", width: 100
				, formatter: function(value, rowData, rowIndex) {
					if (value) {
						ajaxGet("/shizhuang_category/selectById", {
							id: value
						}, function (resp) {
							let data = resp.data;

							ajaxGet("/gender/selectById", {
								id: rowData.gender
							}, function (resp) {
								let gender = resp.data;

								$("#parent_" + rowIndex).html(data.name + " · " + gender.name);
							}, error);
						}, error);

						return "<div id='parent_" + rowIndex + "'></div>";
					}

					return "/";
				}
			}, deleteColumn
		]],
		view: detailview,
		detailFormatter: function(rowIndex, rowData) {
			return "<div id='detail_view_" + rowData.id + "'></div>";
		},
		onExpandRow: function(rowIndex, rowData){
			if (rowData.isParent) {
				$("#detail_view_" + rowData.id).datalist({
					url: "/shizhuang_category/selectByParentId",
					valueField: "id",
					textField: "name",
					queryParams: {
						parentId: rowData.id
					},
					width: 400,
					checkbox: true,
					textFormatter: function(value, rowData, rowIndex) {
						let content = "";

						content += "<table>";
						content += 	"<tr>";
						content += 		"<td rowspan='2'>";
						content += 			"<img height='50' src='" + rowData.image + "' />";
						content += 		"</td>";
						content += 		"<td>" + rowData.name + "</td>";
						content += 	"</tr>";
						content += 	"<tr>";
						content += 		"<td>颜色：<span id='_color_" + rowIndex + "'></span></td>";
						content += 	"</tr>";
						content += "</table>";

						ajaxGet("/color/selectById", {
							id: rowData.colorId
						}, function (resp) {
							let data = resp.data;

							$("#_color_" + rowIndex).html(data.name);
						});

						return content;
					}
				});
			} else {
				$("#detail_view_" + rowData.id).html("<div>当前时装类型无子分类</div>");
			}

			$("#shizhuang_list").datagrid("fixDetailRowHeight", rowIndex);
		}
	});

});